package com.httpapi;

import android.util.Log;

import com.httpapi.apiservice.HttpCode;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import io.reactivex.subscribers.DisposableSubscriber;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

public abstract class RxSubscriber<T> extends DisposableSubscriber<T> {
    public RxSubscriber() {
        super();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onComplete() {

    }

    private String getMsgByThrowable(Throwable e){
        if (e instanceof UnknownHostException) {
            return "没有网络";
        } else if (e instanceof HttpException) {
            return "网络错误";
        } else if (e instanceof SocketTimeoutException) {
            return "网络连接超时";
        } else if (e instanceof ConnectException) {
           return "连接失败";
        } else{
            return "未知错误";
        }
    }

    @Override
    public void onError(Throwable e) {
        String message;
        int code = -1;
        if (e instanceof HttpException){
            ResponseBody body = ((HttpException) e).response().errorBody();
            try {
                //todo 失败时，不解析，那么解析拿什么呢？
                String strResult = body.string();
                BaseResultEntity resultEntity = QHttpApi.gson.fromJson(strResult, BaseResultEntity.class);
                Log.i("httpError3", "onFailure: "+resultEntity.getMessage());
                message=resultEntity.getMessage();
            } catch (IOException es) {
                es.printStackTrace();
                message= getMsgByThrowable(e);
            }
        }else {
            message= getMsgByThrowable(e);
        }
        //Query map contained null value for key 'projectId'. (parameter #2)
        //        for method HttpApiService.doGet
        Log.e("httpError2",e.getLocalizedMessage());

        onFailure(message, code);
    }

    @Override
    public void onNext(T t) {
        if (t == null) {
            onFailure("请求出错，请稍后再试", -1);
            return;
        }
        // 错误统一处理
        BaseResultEntity base = (BaseResultEntity)t;
        int code = base.getCode();
        if (code == HttpCode.SUCCESS) {
            // 服务端返回成功
            onSuccess(t);
        } else {
            String errorMsg = base.getMessage();

            // 公共错误逻辑处理
            switch (code) {
                case HttpCode.ERROR_LOGIN_INVALID:
                    break;
                default:
                    break;
            }

            // 服务端返回错误
            onFailure(errorMsg, code);
        }
    }

    /**
     * success
     *
     * @param t
     */
    public abstract void onSuccess(T t);

    /**
     * failure
     *
     * @param msg
     */
    public abstract void onFailure(String msg, int code);
}
